package agentV1

import (
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"hc_server/pkg/app"
	"hc_server/pkg/channel"
	"hc_server/pkg/file"
	"hc_server/routers/api"
	"hc_server/routers/service/merchantService"
	"hc_server/runtime/e"
)

type MerchantManagerListParam struct {
	Type interface{} `json:"type,omitempty"` // 0: 直属商户 1: 下级商户
}

// MerchantManagerList 商户列表
func MerchantManagerList(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		param   MerchantManagerListParam
		errCode int
	)

	_, errCode = app.BindJsonAndValid(c, &param)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	userId, exists := c.Get("userId")
	if !exists {
		appG.ResponseError("用户不存在", nil)
		return
	}

	merchantService := merchantService.Merchant{UserId: cast.ToInt(userId), Type: cast.ToInt(param.Type)}
	result := merchantService.MerchantGetMerchantList()

	appG.ResponseSuccess("成功", result)
}

type MerchantManagerSearchParam struct {
	Type         interface{} `json:"type,omitempty"`                                         //0: 直属商户 1: 下级商户
	Info         string      `json:"info,omitempty" binding:"omitempty"`                     //商户名称/商户编号
	Name         string      `json:"name,omitempty" binding:"omitempty"`                     //商户全称
	MerchantType any         `json:"merchantType,omitempty" binding:"omitempty,min=0,max=3"` //商户类型 0=全部 1=小微 2=个体 3=企业
	ShopType     any         `json:"shopType,omitempty" binding:"omitempty,min=0,max=4"`     //店铺类型 0=全部 1=总店 2=分店 4分账接收方
	AuditType    any         `json:"auditType,omitempty" binding:"omitempty,min=0,max=3"`    //审核状态 0=全部 1=审核通过 2=审核中 3=驳回
	WechatType   any         `json:"wechatType,omitempty" binding:"omitempty,min=0,max=2"`   //微信认证状态 0=全部 1=未认证 2=已认证
	AliType      any         `json:"aliType,omitempty" binding:"omitempty,min=0,max=2"`      //支付宝认证状态 0=全部 1=未认证 2=已认证
	SubmitTime   string      `json:"submitTime,omitempty"`                                   //提交时间 YYYY-MM-DD hh:mm:ss
	AuditTime    string      `json:"auditTime,omitempty"`                                    //审核时间 YYYY-MM-DD hh:mm:ss
	ActivityId   any         `json:"activityId,omitempty"`                                   //活动id
	SalesmenId   any         `json:"salesmenId,omitempty"`                                   //业务经理id
}

// MerchantManagerSearch 商户管理商户搜索
func MerchantManagerSearch(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		param   MerchantManagerSearchParam
		errCode int
	)

	_, errCode = app.BindJsonAndValid(c, &param)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	userId, exists := c.Get("userId")
	if !exists {
		appG.ResponseError("用户不存在", nil)
		return
	}

	shopType := cast.ToInt(param.ShopType)
	auditType := cast.ToInt(param.AuditType)
	wechatType := cast.ToInt(param.WechatType)
	aliType := cast.ToInt(param.AliType)
	activityId := cast.ToInt(param.ActivityId)
	salesmenId := cast.ToInt(param.SalesmenId)
	merchantType := cast.ToInt(param.MerchantType)

	merchantService := merchantService.Merchant{
		AgentId:    cast.ToInt(userId),
		Type:       cast.ToInt(param.Type),
		Info:       &param.Info,
		Name:       &param.Name,
		MerType:    &merchantType,
		ShopType:   &shopType,
		AuditType:  &auditType,
		WechatType: &wechatType,
		AliType:    &aliType,
		SubmitTime: &param.SubmitTime,
		AuditTime:  &param.AuditTime,
		ActivityId: &activityId,
		SaleId:     &salesmenId,
	}

	result := merchantService.MerchantManagerSearch()
	appG.ResponseSuccess("成功", result)
}

type MerchantManagerInfoParam struct {
	MerchantId interface{} `json:"merchant_id"`
}

// MerchantManagerInfo 商户管理商户详细
func MerchantManagerInfo(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		param   MerchantManagerInfoParam
		errCode int
	)

	_, errCode = app.BindJsonAndValid(c, &param)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	merchantService := merchantService.Merchant{
		MerchantId: cast.ToInt(param.MerchantId),
	}

	result, err := merchantService.MerchantManagerInfo()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	appG.ResponseSuccess("成功", result)
}

type MerchantSettleUpdateParam struct {
	Id                    string `form:"id"`
	SettleAccountType     string `form:"settleAccountType"`     //结算账户类型：1-法人对私；2-非法人对私；3-法人对公；merchantType=1-小微，该参数必须为1-法人对私
	SettleName            string `form:"settleName"`            //结算户名法人对私结算：与法人姓名一致；非法人对私结算：与非法人身份证信息一致；法人对公结算：与营业执照注册名称一致(非法人对私结算需要传值)
	SettleBankcardNo      string `form:"settleBankcardNo"`      //结算卡号
	SettleBankMobile      string `form:"settleBankMobile"`      //银行预留手机号
	SettleSubbranchCode   string `form:"settleSubbranchCode"`   //开户支行联行号
	SettleIdcardNo        string `form:"settleIdcardNo"`        //结算人身份证号（非法人对私必填）
	SettleIdcardStartDate string `form:"settleIdcardStartDate"` //结算人身份证有效期起始日期（非法人对私必填）格式：yyyy-MM-dd
	SettleIdcardEndDate   string `form:"settleIdcardEndDate"`   //结算人身份证有效期结束日期（非法人对私必填）格式：yyyy-MM-dd
}

// MerchantSettleInfoUpdate 修改商户结算信息
func MerchantSettleInfoUpdate(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		param   MerchantSettleUpdateParam
		errCode int
	)

	_, errCode = app.BindAndValid(c, &param)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	//结算卡正面照(图片id)（对公上传开户许可证）
	settleBankcardFrontPic, err := api.VerifyFileAndSave(c, "settleBankcardFrontPic", file.GetRandomFileName(), file.GetFileUserPath(cast.ToString(param.Id)))
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	var fileList = make([]*channel.LianImgUploadParam, 0)
	//fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: file.GetImageFullUrl("user/merchantV1/"+form.Id, settleBankcardFrontPic), Remarks: "settleBankcardFrontPic"})
	fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: "https://pic4.zhimg.com/80/v2-94a0bc8b2774dc9a4dc9a7a01981d30b_720w.jpg", Remarks: "settleBankcardFrontPic"})
	var settleIdcardFrontPic, settleIdcardBackPic, settleAuthPic string
	if cast.ToInt(param.SettleAccountType) == 2 {
		//结算人身份证正面照(图片id)（非法人对私必填）
		settleIdcardFrontPic, err = api.VerifyFileAndSave(c, "settleIdcardFrontPic", file.GetRandomFileName(), file.GetFileUserPath(cast.ToString(param.Id)))
		if err != nil {
			appG.ResponseError(err.Error(), nil)
			return
		}
		//fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: file.GetImageFullUrl("user/merchantV1/"+form.Id, settleIdcardFrontPic), Remarks: "settleIdcardFrontPic"})
		fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: "https://pic4.zhimg.com/80/v2-94a0bc8b2774dc9a4dc9a7a01981d30b_720w.jpg", Remarks: "settleIdcardFrontPic"})

		//结算人身份证反面照(图片id)（非法人对私必填）
		settleIdcardBackPic, err = api.VerifyFileAndSave(c, "settleIdcardBackPic", file.GetRandomFileName(), file.GetFileUserPath(cast.ToString(param.Id)))
		if err != nil {
			appG.ResponseError(err.Error(), nil)
			return
		}
		//fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: file.GetImageFullUrl("user/merchantV1/"+form.Id, settleIdcardBackPic), Remarks: "settleIdcardBackPic"})
		fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: "https://pic4.zhimg.com/80/v2-94a0bc8b2774dc9a4dc9a7a01981d30b_720w.jpg", Remarks: "settleIdcardBackPic"})

		//结算授权书图片(图片id)（非法人对私必填）
		settleAuthPic, err = api.VerifyFileAndSave(c, "settleAuthPic", file.GetRandomFileName(), file.GetFileUserPath(cast.ToString(param.Id)))
		if err != nil {
			appG.ResponseError(err.Error(), nil)
			return
		}
		//fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: file.GetImageFullUrl("user/merchantV1/"+form.Id, settleAuthPic), Remarks: "settleAuthPic"})
		fileList = append(fileList, &channel.LianImgUploadParam{OutFileUrl: "https://pic4.zhimg.com/80/v2-94a0bc8b2774dc9a4dc9a7a01981d30b_720w.jpg", Remarks: "settleAuthPic"})

	}
	err = channel.LianImgUpload(fileList, cast.ToString(param.Id))
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	merchantService := &merchantService.Merchant{
		Id:                     cast.ToInt(param.Id),
		SettleAccountType:      cast.ToInt(param.SettleAccountType),
		SettleBankcardFrontPic: settleBankcardFrontPic,
		SettleName:             param.SettleName,
		SettleBankcardNo:       param.SettleBankcardNo,
		SettleBankMobile:       param.SettleBankMobile,
		SettleSubbranchCode:    param.SettleSubbranchCode,
		SettleIdcardFrontName:  settleIdcardFrontPic,
		SettleIdcardBackName:   settleIdcardBackPic,
		SettleAuthName:         settleAuthPic,
		SettleIdcardNo:         param.SettleIdcardNo,
		SettleIdcardStartDate:  param.SettleIdcardStartDate,
		SettleIdcardEndDate:    param.SettleIdcardEndDate,
	}
	result, err := merchantService.MerchantSettleInfoUpdate()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	appG.ResponseSuccess("修改成功", result)
}

type MerchantShopNameUpdateParam struct {
	Id       interface{} `json:"id"`
	ShopName string      `json:"shopName"`
}

// MerchantShopNameUpdate 修改商户简称信息
func MerchantShopNameUpdate(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		param   MerchantShopNameUpdateParam
		errCode int
	)

	_, errCode = app.BindJsonAndValid(c, &param)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	merchantService := merchantService.Merchant{
		Id:           cast.ToInt(param.Id),
		MerchantName: param.ShopName,
	}

	result, err := merchantService.MerchantShopNameUpdate()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	appG.ResponseSuccess("修改成功", result)
}

type MerchantRateRangeParam struct {
	Id interface{} `json:"id"`
}

// MerchantRateRange 商户费率范围查询接口
func MerchantRateRange(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		param   MerchantRateRangeParam
		errCode int
	)

	_, errCode = app.BindJsonAndValid(c, &param)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	merchantService := merchantService.Merchant{
		Id: cast.ToInt(param.Id),
	}

	result, err := merchantService.MerchantRateRange()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	appG.ResponseSuccess("修改成功", result)
}

type MerchantAuditQueryParam struct {
	Id        interface{} `json:"id"`
	AuditType interface{} `json:"auditType"` //审核类型：1-进件审核（入驻+修改）；2-结算信息变更审核
}

// MerchantAuditQuery 商户审核结果查询
func MerchantAuditQuery(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		param   MerchantAuditQueryParam
		errCode int
	)

	_, errCode = app.BindJsonAndValid(c, &param)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	merchantService := merchantService.Merchant{
		Id:          cast.ToInt(param.Id),
		LDAuditType: cast.ToInt(param.AuditType),
	}

	result, err := merchantService.MerchantAuditQuery()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	appG.ResponseSuccess("修改成功", result)
}

type MerchantGetWechatApproveParam struct {
	Id interface{} `json:"id"`
}

// MerchantGetWechatApprove 微信认证查询
func MerchantGetWechatApprove(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		param   MerchantGetWechatApproveParam
		errCode int
	)

	_, errCode = app.BindJsonAndValid(c, &param)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	merchantService := merchantService.Merchant{
		Id: cast.ToInt(param.Id),
	}

	result, err := merchantService.MerchantGetWechatApprove()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	appG.ResponseSuccess("成功", result)
}

type MerchantGetWechatAuthParam struct {
	Id interface{} `json:"id"`
}

// MerchantGetWechatAuth 微信授权状态查询
func MerchantGetWechatAuth(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		param   MerchantGetWechatAuthParam
		errCode int
	)

	_, errCode = app.BindJsonAndValid(c, &param)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	merchantService := merchantService.Merchant{
		Id: cast.ToInt(param.Id),
	}

	result, err := merchantService.MerchantGetWechatAuth()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	appG.ResponseSuccess("成功", result)
}

type MerchantGetAlipayApproveParam struct {
	Id interface{} `json:"id"`
}

// MerchantGetAlipayApprove 支付宝认证查询
func MerchantGetAlipayApprove(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		param   MerchantGetAlipayApproveParam
		errCode int
	)

	_, errCode = app.BindJsonAndValid(c, &param)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	merchantService := merchantService.Merchant{
		Id: cast.ToInt(param.Id),
	}

	result, err := merchantService.MerchantGetAlipayApprove()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	appG.ResponseSuccess("成功", result)
}

type MerchantGetAlipayAuthParam struct {
	Id interface{} `json:"id"`
}

// MerchantGetAlipayAuth 支付宝授权状态查询
func MerchantGetAlipayAuth(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		param   MerchantGetAlipayAuthParam
		errCode int
	)

	_, errCode = app.BindJsonAndValid(c, &param)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	merchantService := merchantService.Merchant{
		Id: cast.ToInt(param.Id),
	}

	result, err := merchantService.MerchantGetAlipayAuth()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	appG.ResponseSuccess("成功", result)
}
